package com.jenvin.idcreator;

import java.util.concurrent.atomic.AtomicLong;

/**
 * 单例化 IdCreator 必须单列的形式注入到spring
 * 
 * @author jenvin 2012-4-14 下午11:38:22
 */
public class IdCreator {

    private final static long DEFAULT_BUFFER_SIZE = 950;
    private long              bufferSize          = DEFAULT_BUFFER_SIZE;
    private IdCreatorProvider provider            = null;
    private AtomicLong        offerset            = null;
    private volatile long     threshold           = 0;
    private long              seed                = 0;
    private String            name                = "";
    private String            description         = "";
    
    public long getNewId() {
        if (offerset == null || offerset.get() > threshold) {
            synchronized (this) {// double check
                if (offerset == null || offerset.get() >= threshold) {
                    long start = provider.aquireIdBuffer(bufferSize, seed, name, description);
                    offerset = new AtomicLong(start + 1);
                    threshold = start + bufferSize;
                }
            }
        }
        return offerset.getAndIncrement();
    }

    public void setBufferSize(long bufferSize) {
        this.bufferSize = bufferSize;
    }

    public long getSeed() {
        return seed;
    }

    public void setSeed(long seed) {
        this.seed = seed;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setProvider(IdCreatorProvider provider) {
        this.provider = provider;
    }

    public IdCreatorProvider getProvider() {
        return provider;
    }
}
